<template>
  <view class="diagnose-page">
    <view class="page-header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="back" size="20" color="#333"></uni-icons>
      </view>
      <text class="header-title">患者诊断</text>
      <view class="header-right"></view>
    </view>
    
    <!-- 患者信息摘要 -->
    <view class="patient-summary" v-if="patient">
      <view class="avatar">
        <uni-icons :type="patient.sex === 'male' ? 'person' : 'person-filled'" size="40" color="#2979ff"></uni-icons>
      </view>
      <view class="info">
        <view class="name-gender">
          <text class="name">{{ patient.name || '未知患者' }}</text>
          <text class="gender">{{ patient.sex === 'male' ? '男' : '女' }} · {{ patient.age || '--' }}岁</text>
        </view>
        <view class="health-tags">
          <uni-tag text="心率正常" type="success" size="small" v-if="healthData && healthData.heartRate && healthData.heartRate >= 60 && healthData.heartRate <= 100"></uni-tag>
          <uni-tag text="心率异常" type="error" size="small" v-else-if="healthData && healthData.heartRate && healthData.heartRate !== '--'"></uni-tag>
          
          <uni-tag text="血压正常" type="success" size="small" v-if="healthData && healthData.bloodPressureHigh && healthData.bloodPressureLow && healthData.bloodPressureHigh <= 140 && healthData.bloodPressureLow <= 90"></uni-tag>
          <uni-tag text="血压异常" type="error" size="small" v-else-if="healthData && (healthData.bloodPressureHigh !== '--' || healthData.bloodPressureLow !== '--')"></uni-tag>
          
          <uni-tag text="血氧正常" type="success" size="small" v-if="healthData && healthData.bloodOxygen && healthData.bloodOxygen >= 95"></uni-tag>
          <uni-tag text="血氧异常" type="error" size="small" v-else-if="healthData && healthData.bloodOxygen && healthData.bloodOxygen !== '--'"></uni-tag>
          
          <uni-tag text="体温正常" type="success" size="small" v-if="healthData && healthData.bodyTemperature && healthData.bodyTemperature >= 36 && healthData.bodyTemperature <= 37.2"></uni-tag>
          <uni-tag text="体温异常" type="error" size="small" v-else-if="healthData && healthData.bodyTemperature && healthData.bodyTemperature !== '--'"></uni-tag>
        </view>
      </view>
      <view class="action">
        <button class="uni-btn" size="mini" type="primary" @click="showAllergies">过敏史</button>
      </view>
    </view>
    
    <uni-segmented-control :current="current" :values="['病历', '处方']" @clickItem="tabChange"></uni-segmented-control>
    
    <!-- 诊断内容区域 -->
    <view class="tab-content">
      <!-- 病历 -->
      <view v-if="current === 0" class="medical-record">
        <uni-forms ref="medicalRecordFormRef" :model="medicalRecordForm" :rules="medicalRecordRules">
          <uni-forms-item label="医院" required name="hospital">
            <uni-easyinput v-model="medicalRecordForm.hospital" placeholder="请输入医院名称" />
          </uni-forms-item>
          
          <uni-forms-item label="科室" required name="department">
            <uni-easyinput v-model="medicalRecordForm.department" placeholder="请输入科室" />
          </uni-forms-item>
          
          <uni-forms-item label="诊断结果" required name="diagnosis">
            <uni-easyinput v-model="medicalRecordForm.diagnosis" type="textarea" placeholder="请输入诊断结果" />
          </uni-forms-item>
          
          <uni-forms-item label="医嘱" required name="advice">
            <uni-easyinput v-model="medicalRecordForm.advice" type="textarea" placeholder="请输入医嘱" />
          </uni-forms-item>
        </uni-forms>
        
        <view class="form-actions">
          <button class="uni-btn" type="primary" @click="saveMedicalRecord">保存病历</button>
        </view>
      </view>
      
      <!-- 处方 -->
      <view v-if="current === 1" class="prescription">
        <view class="medication-list">
          <view v-if="medications.length > 0">
            <view v-for="(med, index) in medications" :key="index" class="medication-item">
              <view class="med-info">
                <view class="med-name">{{ med.medicationName }}</view>
                <view class="med-details">
                  <text>{{ med.dosage }} · {{ med.frequency }}</text>
                </view>
                <view class="med-duration">
                  <text>{{ med.startDate }} 至 {{ med.endDate }}</text>
                </view>
                <view v-if="med.allergy" class="med-allergy">
                  <uni-tag text="过敏药物" type="error" size="small"></uni-tag>
                </view>
              </view>
              <view class="med-actions">
                <button class="uni-btn" size="mini" type="warn" @click="removeMedication(index)">删除</button>
              </view>
            </view>
          </view>
          <view v-else class="empty-meds">
            <uni-empty text="暂无用药"></uni-empty>
          </view>
        </view>
        
        <view class="add-section">
          <view class="section-title">添加药品</view>
          <uni-forms ref="medicationFormRef" :model="medicationForm" :rules="medicationRules">
            <uni-forms-item label="药品名称" required name="medicationName">
              <uni-easyinput v-model="medicationForm.medicationName" placeholder="请输入药品名称" />
            </uni-forms-item>
            
            <uni-forms-item label="剂量" required name="dosage">
              <uni-easyinput v-model="medicationForm.dosage" placeholder="例如：5mg" />
            </uni-forms-item>
            
            <uni-forms-item label="服用频率" required name="frequency">
              <uni-easyinput v-model="medicationForm.frequency" placeholder="例如：每日三次" />
            </uni-forms-item>
            
            <uni-forms-item label="药物描述" name="drugDiscription">
              <uni-easyinput v-model="medicationForm.drugDiscription" type="textarea" placeholder="请输入药物描述" />
            </uni-forms-item>
            
            <uni-forms-item label="服用时间" required>
              <view class="date-picker-group">
                <view class="date-picker">
                  <text class="date-label">开始日期</text>
                  <uni-datetime-picker v-model="medicationForm.startDate" type="date" :clear-icon="false" />
                </view>
                <view class="date-picker">
                  <text class="date-label">结束日期</text>
                  <uni-datetime-picker v-model="medicationForm.endDate" type="date" :clear-icon="false" />
                </view>
              </view>
            </uni-forms-item>
            
            <uni-forms-item label="标记为过敏性药物" name="allergy">
              <switch :checked="medicationForm.allergy" @change="e => medicationForm.allergy = e.detail.value" />
            </uni-forms-item>
          </uni-forms>
          
          <view class="form-actions">
            <button class="uni-btn" type="primary" @click="addMedication">添加药品</button>
          </view>
        </view>
        
        <view class="form-actions prescription-actions">
          <button class="uni-btn" type="primary" @click="savePrescription">保存处方</button>
        </view>
      </view>
    </view>
    
    <uni-popup ref="allergyPopup" type="center">
      <view class="allergies-popup">
        <view class="popup-header">
          <text class="popup-title">过敏药物</text>
          <uni-icons type="close" size="20" @click="showAllergiesList = false; allergyPopup?.close()"></uni-icons>
        </view>
        <view class="popup-content">
          <view v-if="allergyList && allergyList.length > 0">
            <view v-for="allergy in allergyList" :key="allergy.id" class="allergy-item">
              <uni-icons type="warning" color="#fa3534" size="18"></uni-icons>
              <text class="allergy-name">{{ allergy.medicationName }}</text>
            </view>
          </view>
          <view v-else class="empty-allergies">
            <uni-empty text="暂无过敏药物记录"></uni-empty>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { usePatientStore } from '@/store/modules/useDoctorStore';
import { useRecordStore } from '@/store/modules/useRecordStore';
import { useHealthData } from '@/store/modules/useHealthData';

// 组件引用
const medicalRecordFormRef = ref(null);
const medicationFormRef = ref(null);
const allergyPopup = ref(null);

// 状态管理
const patientStore = usePatientStore();
const recordStore = useRecordStore();
const healthDataStore = useHealthData();

// 页面状态
const current = ref(0);
const loading = ref(false);
const patientId = ref(null);
const showAllergiesList = ref(false);
const medications = ref([]);

// 患者数据
const patient = ref(null);
const healthData = ref(null);
const allergyList = ref([]);

// 表单验证规则
const medicalRecordRules = {
  hospital: {
    rules: [{
      required: true,
      errorMessage: '请输入医院名称'
    }]
  },
  department: {
    rules: [{
      required: true,
      errorMessage: '请输入科室'
    }]
  },
  diagnosis: {
    rules: [{
      required: true,
      errorMessage: '请输入诊断结果'
    }]
  },
  advice: {
    rules: [{
      required: true,
      errorMessage: '请输入医嘱'
    }]
  }
};

const medicationRules = {
  medicationName: {
    rules: [{
      required: true,
      errorMessage: '请输入药品名称'
    }]
  },
  dosage: {
    rules: [{
      required: true,
      errorMessage: '请输入剂量'
    }]
  },
  frequency: {
    rules: [{
      required: true,
      errorMessage: '请输入服用频率'
    }]
  }
};

// 病历表单
const medicalRecordForm = reactive({
  hospital: '',
  department: '',
  diagnosis: '',
  advice: '',
  time: new Date().toISOString()
});

// 药物表单
const medicationForm = reactive({
  medicationName: '',
  dosage: '',
  frequency: '',
  drugDiscription: '',
  startDate: formatDate(new Date()),
  endDate: formatDate(new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)),
  allergy: false
});

// 检查表单日期
const checkDates = computed(() => {
  if (!medicationForm.startDate || !medicationForm.endDate) {
    return false;
  }
  
  const start = new Date(medicationForm.startDate);
  const end = new Date(medicationForm.endDate);
  
  return end >= start;
});

// 加载患者数据
const loadPatientData = async (id) => {
  if (!id) return;
  
  patientId.value = id;
  loading.value = true;
  
  try {
    // 先设置当前患者ID，这会触发相关数据的加载
    await patientStore.setCurPatientId(id);
    
    // 设置记录store的当前用户ID
    recordStore.setCurUserId(id);
    
    // 并行获取所有需要的数据
    const [allergyListResult, healthDataResult] = await Promise.all([
      recordStore.fetchAllergyList(id),
      healthDataStore.fetchRealtimeData(id)
    ]);
    
    // 更新本地状态
    patient.value = patientStore.getCurPatient;
    healthData.value = healthDataStore.getRealtimeHealthData;
    allergyList.value = recordStore.getAllergyList;
    
    // 预填医院和科室信息
    medicalRecordForm.hospital = '互联网医院';
    medicalRecordForm.department = '内科';
    
    console.log('患者数据加载成功:', {
      patient: patient.value,
      healthData: healthData.value,
      allergyList: allergyList.value
    });
  } catch (error) {
    console.error('加载患者数据失败:', error);
    uni.showToast({
      title: '加载数据失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 使用计算属性来获取数据
const patientData = computed(() => patientStore.getCurPatient);
const healthDataValue = computed(() => healthDataStore.getRealtimeHealthData);
const allergyListData = computed(() => recordStore.getAllergyList);

// 监听计算属性的变化
watch(patientData, (newVal) => {
  if (newVal) {
    patient.value = newVal;
  }
}, { immediate: true });

watch(healthDataValue, (newVal) => {
  if (newVal) {
    healthData.value = newVal;
  }
}, { immediate: true });

watch(allergyListData, (newVal) => {
  if (newVal) {
    allergyList.value = newVal;
  }
}, { immediate: true });

// 页面加载时获取参数
onMounted(() => {
  // 获取当前页面实例
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  
  // 尝试多种方式获取参数
  let id = null;
  
  // 方式1：从options中获取
  if (currentPage?.options?.id) {
    id = currentPage.options.id;
  }
  
  // 方式2：从$page中获取
  if (!id && currentPage?.$page?.options?.id) {
    id = currentPage.$page.options.id;
  }
  
  // 方式3：从路由参数中获取
  if (!id && currentPage?.$page?.fullPath) {
    const query = currentPage.$page.fullPath.split('?')[1];
    if (query) {
      const params = new URLSearchParams(query);
      id = params.get('id');
    }
  }
  
  // 方式4：从onLoad参数中获取
  if (!id && currentPage?.$vm?.$scope?.options?.id) {
    id = currentPage.$vm.$scope.options.id;
  }
  
  console.log('诊断页面参数获取结果:', {
    currentPage,
    id,
    options: currentPage?.options,
    $page: currentPage?.$page,
    $vm: currentPage?.$vm
  });
  
  if (id) {
    console.log('加载患者诊断页，患者ID:', id);
    loadPatientData(id);
  } else {
    console.error('未获取到患者ID参数');
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    });
    setTimeout(() => {
      goBack();
    }, 1500);
  }
});

// 切换标签
const tabChange = (e) => {
  current.value = e.currentIndex;
};

// 显示过敏药物
const showAllergies = () => {
  showAllergiesList.value = true;
  allergyPopup.value?.open();
};

// 添加药物
const addMedication = () => {
  // 检查日期
  if (!checkDates.value) {
    uni.showToast({
      title: '结束日期不能早于开始日期',
      icon: 'none'
    });
    return;
  }
  
  // 如果组件引用存在则使用组件验证
  if (medicationFormRef.value) {
    medicationFormRef.value.validate().then(res => {
      addValidatedMedication();
    }).catch(err => {
      console.log('表单错误：', err);
    });
  } else {
    // 手动验证必填项
    if (!medicationForm.medicationName) {
      uni.showToast({
        title: '请输入药品名称',
        icon: 'none'
      });
      return;
    }
    if (!medicationForm.dosage) {
      uni.showToast({
        title: '请输入剂量',
        icon: 'none'
      });
      return;
    }
    if (!medicationForm.frequency) {
      uni.showToast({
        title: '请输入服用频率',
        icon: 'none'
      });
      return;
    }
    // 验证通过，添加药物
    addValidatedMedication();
  }
};

// 添加验证通过的药物
const addValidatedMedication = () => {
  const medication = {
    medicationName: medicationForm.medicationName,
    dosage: medicationForm.dosage,
    frequency: medicationForm.frequency,
    drugDiscription: medicationForm.drugDiscription,
    startDate: medicationForm.startDate,
    endDate: medicationForm.endDate,
    allergy: medicationForm.allergy,
  };
  
  medications.value.push({...medication});
  
  // 重置表单
  medicationForm.medicationName = '';
  medicationForm.dosage = '';
  medicationForm.frequency = '';
  medicationForm.drugDiscription = '';
  medicationForm.allergy = false;
  medicationForm.startDate = formatDate(new Date());
  medicationForm.endDate = formatDate(new Date(Date.now() + 7 * 24 * 60 * 60 * 1000));
  
  uni.showToast({
    title: '药品添加成功',
    icon: 'success'
  });
};

// 移除药物
const removeMedication = (index) => {
  medications.value.splice(index, 1);
  uni.showToast({
    title: '已删除药品',
    icon: 'none'
  });
};

// 保存病历
const saveMedicalRecord = async () => {
  if (!medicalRecordFormRef.value) {
    uni.showToast({
      title: '表单未准备好',
      icon: 'none'
    });
    return;
  }
  
  try {
    const valid = await medicalRecordFormRef.value.validate();
    if (valid) {
      loading.value = true;
      const record = {
        hospital: medicalRecordForm.hospital,
        department: medicalRecordForm.department,
        diagnosis: medicalRecordForm.diagnosis,
        advice: medicalRecordForm.advice,
        time: medicalRecordForm.time
      };
      
      await recordStore.addMedicalRecord(record);
      
      uni.showToast({
        title: '病历保存成功',
        icon: 'success'
      });
      
      setTimeout(() => {
        current.value = 1;
      }, 0);
    }
  } catch (error) {
    console.error('保存病历失败:', error);
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 保存处方
const savePrescription = async () => {
  if (medications.value.length === 0) {
    uni.showToast({
      title: '请至少添加一种药物',
      icon: 'none'
    });
    return;
  }
  
  loading.value = true;
  try {
    const medicinesToSave = [...medications.value];
    
    // 批量保存前的提示
    uni.showToast({
      title: `正在保存${medicinesToSave.length}种药物...`,
      icon: 'loading',
      duration: 2000
    });
    
    // 保存所有药物
    for (const med of medicinesToSave) {
      try {
        if (med.allergy) {
          await recordStore.addAllergy({...med});
        } else {
          await recordStore.addMedication({...med});
        }
      } catch (err) {
        console.error(`保存药物 ${med.medicationName} 失败:`, err);
      }
    }
    
    // 清空本地列表
    medications.value = [];
    
    uni.showToast({
      title: '处方保存成功',
      icon: 'success'
    });
    
    // 返回上一页
    setTimeout(() => {
      goBack();
    }, 1500);
    
  } catch (error) {
    console.error('保存处方失败:', error);
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 返回上一页
const goBack = () => {
  // 如果有未保存的药物或病历数据，提示用户
  if ((current.value === 0 && (medicalRecordForm.diagnosis || medicalRecordForm.advice)) || 
      (current.value === 1 && medications.value.length > 0)) {
    uni.showModal({
      title: '提示',
      content: '您有未保存的数据，确定要离开吗？',
      success: (res) => {
        if (res.confirm) {
          uni.navigateBack();
        }
      }
    });
  } else {
    uni.navigateBack();
  }
};

// 格式化日期
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
</script>

<style lang="scss" scoped>
.diagnose-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  
  .back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .header-title {
    flex: 1;
    text-align: center;
    font-size: 34rpx;
    font-weight: bold;
  }
  
  .header-right {
    width: 60rpx;
  }
}

.patient-summary {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  margin-bottom: 1px;
  
  .avatar {
    margin-right: 20rpx;
  }
  
  .info {
    flex: 1;
    
    .name-gender {
      margin-bottom: 10rpx;
      
      .name {
        font-size: 30rpx;
        font-weight: bold;
        margin-right: 15rpx;
      }
      
      .gender {
        font-size: 24rpx;
        color: #666;
      }
    }
    
    .health-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 10rpx;
    }
  }
}

.tab-content {
  padding: 30rpx;
}

.form-actions {
  margin-top: 40rpx;
  margin-bottom: 60rpx;
}

.prescription-actions {
  margin-top: 60rpx;
}

.medication-list {
  margin-bottom: 40rpx;
  
  .medication-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #ffffff;
    padding: 20rpx;
    border-radius: 10rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    
    .med-info {
      flex: 1;
      
      .med-name {
        font-size: 28rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
      }
      
      .med-details, .med-duration {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 5rpx;
      }
      
      .med-allergy {
        margin-top: 8rpx;
      }
    }
    
    .med-actions {
      margin-left: 20rpx;
    }
  }
  
  .empty-meds {
    padding: 40rpx 0;
  }
}

.add-section {
  background-color: #ffffff;
  padding: 30rpx;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  
  .section-title {
    font-size: 30rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
  }
}

.date-picker-group {
  display: flex;
  justify-content: space-between;
  
  .date-picker {
    width: 48%;
    
    .date-label {
      font-size: 24rpx;
      color: #666;
      margin-bottom: 10rpx;
      display: block;
    }
  }
}

.allergies-popup {
  padding: 30rpx;
  width: 500rpx;
  background-color: #fff;
  border-radius: 16rpx;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
    }
  }
  
  .popup-content {
    max-height: 600rpx;
    overflow-y: auto;
  }
  
  .allergy-item {
    display: flex;
    align-items: center;
    padding: 15rpx 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .allergy-name {
      margin-left: 15rpx;
      font-size: 28rpx;
    }
  }
  
  .empty-allergies {
    padding: 40rpx 0;
  }
}
</style>
